<template>
  <q-page class="flex flex-center column q-pa-md">
    <img
      src="https://zhuchundashuaige.s3.eu-north-1.amazonaws.com/public/images/logo.png"
      alt="Windows"
      class="q-mb-md"
      style="width: 80px"
      v-if="!isLoggedIn"
    />

    <div
      class="q-gutter-md"
      style="max-width: 400px; width: 100%; margin-top: 20px"
    >
      <q-input
        v-model="email"
        label="请输入邮箱"
        outlined
        dense
        type="email"
        :rules="[(val) => !!val || '邮箱不能为空', isValidEmail]"
        @keyup.enter="handleNext"
        v-if="!isLoggedIn"
      />

      <q-btn
        color="primary"
        label="下一步"
        :disable="loading"
        @click="handleNext"
        class="q-mx-auto"
        style="display: block; width: fit-content"
        v-if="!isLoggedIn"
      />

      <div v-if="isLoggedIn" class="text-center">
        <q-avatar size="80px" class="q-mb-sm">
          <img
            src="https://zhuchundashuaige.s3.eu-north-1.amazonaws.com/public/images/logo.png"
            alt="User"
          />
        </q-avatar>
        <div class="text-h6 q-mb-xs">欢迎回来：{{ userInfo.displayName }}</div>
        <div class="text-subtitle1 text-grey">{{ userInfo.email }}</div>
        <q-btn color="negative" label="退出登录" class="q-mt-md">
          <q-menu>
            <q-list style="min-width: 150px">
              <q-item clickable v-close-popup @click="handleLogout">
                <q-item-section>仅退出当前登录</q-item-section>
              </q-item>
              <q-item clickable v-close-popup @click="handleMicrosoftLogout">
                <q-item-section>注销微软账号</q-item-section>
              </q-item>
            </q-list>
          </q-menu>
        </q-btn>
        <div class="q-mt-md" />
        <div class="text-subtitle1 text-grey">
          登录于: {{ formatDate(userInfo.tokenIat) }}
        </div>
        <div class="text-subtitle1 text-grey">倒计时: {{ countdown }}</div>
      </div>
    </div>
  </q-page>
</template>

<script setup>
import { api } from "src/boot/axios";
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { Notify, Loading, LoadingBar, QSpinnerIos } from "quasar";
import {
  initializeMsal,
  msalInstance,
  loginRequest,
} from "src/msal/authConfig";
import {
  getAccount,
  getAccessToken,
  handleRedirectCallback,
} from "src/msal/authService";

defineOptions({
  name: "IndexPage",
});

const email = ref("");
const appConfig = ref({});
const loading = ref(false);
const isLoggedIn = ref(false);
const userInfo = ref(JSON.parse(localStorage.getItem("userInfo")) || {});

const isValidEmail = (val) => {
  const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return pattern.test(val) || "邮箱格式不正确";
};

LoadingBar.setDefaults({ color: "primary" });

Loading.setDefaults({
  spinner: QSpinnerIos,
  spinnerSize: 40,
  spinnerColor: "grey-8",
  backgroundColor: "grey-3",
});

const formatDate = (date) => {
  if (!date) return "未知";
  return new Date(date).toLocaleString();
};

const getTokenExpiryCountdown = () => {
  if (!userInfo.value.tokenExp) return "未知";

  const now = new Date();
  const expiry = new Date(userInfo.value.tokenExp);
  if (now > expiry) return "已过期";

  const diff = expiry - now;
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

const countdown = ref("计算中...");
const updateCountdown = () => {
  countdown.value = getTokenExpiryCountdown();
};

const handleNext = async () => {
  try {
    if (!isValidEmail(email.value)) return;

    loading.value = true;
    Loading.show();

    // 新增环境判断逻辑
    const hostname = window.location.hostname;
    const env = ["127.0.0.1", "localhost"].includes(hostname) ? "dev" : "prod";

    const appRes = await api.get("/api/v1/app_config", {
      params: {
        email: email.value,
        env: env, // 使用动态环境变量
      },
    });

    appConfig.value = appRes.data;
    localStorage.setItem("appConfig", JSON.stringify(appConfig.value));
    localStorage.setItem("email", email.value);
    location.reload();
  } catch (error) {
    Notify.create({
      type: "negative",
      message:
        "获取应用配置失败，请稍后重试。请检查邮箱是否正确或者联系管理员。support@zhuchundashuaige.com",
    });
    console.log("Error fetching application config:", error);
  } finally {
    loading.value = false;
    Loading.hide();
  }
};

async function processSSOLogin() {
  try {
    // 新增 try-catch
    Loading.show();
    const response = await handleRedirectCallback();

    if (response) {
      Loading.show();
      const token = await getAccessToken();
      // console.log('token', token);
      const access_token = await acquireAccessToken(token);
      console.log("Access Token:", access_token);
      $q.notify({
        type: "positive",
        message: "SSO Login with Microsoft Account Success!",
      });
    } else {
      console.log("There is no callback yet, waiting for next move");
    }
  } catch (error) {
    console.error("SSO Login Error:", error);
    $q.notify({
      type: "negative",
      message: "请检查你是否在多个地方尝试登录操作？或者关闭所有浏览器重试",
    });
  } finally {
    Loading.hide();
  }
}

async function handleResponse(response) {
  if (response !== null) {
    msalInstance
      .acquireTokenSilent({
        scopes: loginRequest.scopes,
        account: response.account,
      })
      .then((tokenResponse) => {
        console.log(
          "Access token acquired silently:",
          tokenResponse.accessToken
        );
        localStorage.setItem("token", tokenResponse.accessToken);
        location.reload();
      })
      .catch((error) => {
        console.error("Silent token acquisition failed:", error);
        // window.location.href = "/";
        return;
      });
  } else {
    // window.location.href = "/";
    const currentAccounts = msalInstance.getAllAccounts();
    if (!currentAccounts) {
      return;
    }
    const account = currentAccounts[0];
    if (account) {
      msalInstance
        .acquireTokenSilent({
          scopes: loginRequest.scopes,
          account: account,
        })
        .then((tokenResponse) => {
          console.log(
            "Access token acquired silently:",
            tokenResponse.accessToken
          );
          localStorage.setItem("token", tokenResponse.accessToken);
        });
    } else {
      console.log("Not logged in");
      await processSSOLogin();
    }
  }
}

async function handleLogout() {
  localStorage.removeItem("token");
  localStorage.removeItem("userInfo");
  location.reload();
}

async function handleMicrosoftLogout() {
  try {
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
    localStorage.setItem("loginOut", "true");
    location.reload();
  } catch (error) {
    console.error("Microsoft logout failed:", error);
    Notify.create({
      type: "negative",
      message: "注销微软账号失败",
    });
  }
}

async function VerifyToken(token, email) {
  try {
    Loading.show();
    const res = await api.post("/api/v1/user_info", null, {
      headers: {
        ApiKey: btoa(`${token}` + "$$" + `${email}`),
      },
    });

    if (!res.data) {
      throw new Error("验证响应数据为空");
    }

    try {
      const redirectUri = localStorage.getItem("redirectUri") || "";
      if (redirectUri) {
        localStorage.removeItem("redirectUri");
        localStorage.removeItem("redirectUriType");
        const localStorageJson = JSON.stringify(localStorage);
        // to Base64
        const base64 = btoa(
          encodeURIComponent(localStorageJson).replace(
            /%([0-9A-F]{2})/g,
            (match, p1) => String.fromCharCode(parseInt(p1, 16))
          )
        );
        // add to redirectUri
        if (localStorage.getItem("redirectUriType")) {
          const redirectUriWithParamsPSA = `${redirectUri}/#/?LoginData=${base64}`;
          window.location.href = redirectUriWithParamsPSA;
        } else {
          const redirectUriWithParams = `${redirectUri}?LoginData=${base64}`;
          window.location.href = redirectUriWithParams;
        }
      }
    } catch (ex) {
      console.error(ex);
    }

    const parseJwt = (token) => {
      try {
        const base64Url = token.split(".")[1];
        const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
        const jsonPayload = decodeURIComponent(
          atob(base64)
            .split("")
            .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
            .join("")
        );
        return JSON.parse(jsonPayload);
      } catch (e) {
        return null;
      }
    };
    const tokenPayload = parseJwt(token);
    console.log("解析的JWT payload:", tokenPayload);

    userInfo.value = {
      email: res.data.email,
      id: res.data.user_id,
      displayName: res.data.display_name,
      name: res.data.given_name,
      tokenExp: tokenPayload?.exp ? new Date(tokenPayload.exp * 1000) : null,
      tokenIat: tokenPayload?.iat ? new Date(tokenPayload.iat * 1000) : null,
    };
    localStorage.setItem("userInfo", JSON.stringify(userInfo.value));

    Notify.create({
      type: "positive",
      message: "验证成功",
    });
    isLoggedIn.value = true;
  } catch (error) {
    console.error("Token验证失败:", error);
    Notify.create({
      type: "negative",
      message: "Token验证失败，请重新登录",
    });
    localStorage.removeItem("token");
    window.location.reload();
  } finally {
    Loading.hide();
  }
}

const expirationTimer = ref(null);
const version = ref("1.1");
onMounted(async () => {
  const appVersion = localStorage.getItem("version") || "";
  if (appVersion !== version.value) {
    localStorage.setItem("version", version.value);
    localStorage.removeItem("token");
    localStorage.removeItem("email");
    localStorage.removeItem("appConfig");
  }
  const router = useRouter();
  const redirectUri = router.currentRoute.value.query.RedirectUri;
  if (redirectUri) {
    const uriType = router.currentRoute.value.query.Type || "SPA";
    localStorage.setItem("redirectUri", redirectUri);
    localStorage.setItem("redirectUriType", uriType);
  }
  const storedEmail = localStorage.getItem("email");
  if (storedEmail) {
    email.value = storedEmail;
  }

  const isLoginOut = router.currentRoute.value.query.LoginOut;
  const loginOutEmail = router.currentRoute.value.query.LoginOutEmail;

  const token = localStorage.getItem("token");
  if (token && email.value) {
    console.log("Token already exists:", token);
    await VerifyToken(token, email.value);

    // 立即更新一次倒计时
    updateCountdown();
    // 设置定时器每秒更新一次
    const countdownInterval = setInterval(updateCountdown, 1000);

    const checkTokenExpiration = () => {
      if (
        userInfo.value.tokenExp &&
        new Date() > new Date(userInfo.value.tokenExp)
      ) {
        clearInterval(countdownInterval); // 清除倒计时定时器
        console.log("Token已过期，清除本地存储");
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        isLoggedIn.value = false;
        userInfo.value = {};
        Notify.create({
          type: "warning",
          message: "登录已过期，请重新登录",
        });
      }
    };

    expirationTimer.value = setInterval(checkTokenExpiration, 1 * 1000);
    return;
  }

  const appConfigJSON = localStorage.getItem("appConfig");
  if (appConfigJSON) {
    appConfig.value = JSON.parse(appConfigJSON);
    if (
      !appConfig.value.clientId ||
      !appConfig.value.authority ||
      !appConfig.value.redirectUri
    ) {
      Notify.create({
        type: "warning",
        message: "应用配置不完整，请重新输入邮箱。",
      });
      localStorage.removeItem("appConfig");
      localStorage.removeItem("email");
    } else {
      await initializeMsal();
      console.log("MSAL initialized with appConfig:", appConfig.value);
      Loading.show();
      if (localStorage.getItem("loginOut") === "true") {
        localStorage.clear();
        await msalInstance.logoutRedirect();
        return;
      }
      if (isLoginOut && email.value == loginOutEmail) {
        localStorage.clear();
        await msalInstance.logoutRedirect();
        return;
      }
      // if (!account) {
      //   console.log("Not logged in");
      //   await processSSOLogin();
      // } else {
      //   // 如果URL包含微软重定向返回的信息（code），则进行处理
      //   console.log("Already logged in");
      //   msalInstance
      //     .handleRedirectPromise()
      //     .then(handleResponse)
      //     .catch((error) => {
      //       console.error(error);
      //     });
      // }
      msalInstance
        .handleRedirectPromise()
        .then(handleResponse)
        .catch((error) => {
          console.error(error);
        })
        .finally(() => {
          Loading.hide();
        });
      // signIn();
    }
  }
});

onUnmounted(() => {
  clearInterval(expirationTimer);
});
</script>
